import { Component, OnInit, Output, EventEmitter } from '@angular/core';

import { TreeModule, TreeNode } from 'primeng/primeng';

import { HintsService } from 'app/public/serve/hints/hints.service';
import { TreeService } from 'app/public/serve/tree/tree.service';

import { app } from '../application.data';
import { appUrl } from '../application.url';

@Component({
  selector: 'tree',
  templateUrl: './tree.component.html',
  styleUrls: ['./tree.component.css']
})

export class TreeComponent implements OnInit {

  @Output() tree = new EventEmitter<void>();
  @Output() nodeSelect = new EventEmitter<void>();

  treeData     : TreeNode[];
  selectedFile : TreeNode[];

  constructor(
    private treeService: TreeService,
    private hintsService: HintsService
  ) { }

  ngOnInit() {
    this._tree();
  }

  /**
   * 选中的节点
   * @param event 
   * @param id 
   */
  _nodeSelect(event, id) {

    if ((event.node.institutionName as string).indexOf("已禁用") > -1) {
      app['isDisable'] = true;
    }else {
      app['isDisable'] = false;      
    }

    app.tree.institutionName = event.node.institutionName;
    app.tree.institutionId   = event.node.institutionId;
    app.tree.parentId        = event.node.parentId;

    this.nodeSelect.emit();

  }

  /**
   * 树状图
   */ 
  _tree() {
    this.treeService
        .getParentInfos(appUrl.getParentInfos, 'institutionId', 'institutionName')
        .then((res: any) => {
          this.treeData = res;
          app.tree.institutionName = this.treeData[0]['institutionName'];
          app.tree.institutionId   = this.treeData[0]['institutionId'];
          app.tree.parentId        = this.treeData[0]['parentId'];

          // 默认选中第一个节点（注释部分为：展开第一个节点）
          this.selectedFile = [this.treeData[0]];
          // this.treeData[0].expanded = true;
          // 展开所有节点
          this._expandAll();

          this.tree.emit();
        })
        .catch((err: any) => {
          this.hintsService._operationHints('error', 'error');
          return
        });
  }

  /**
   * 已禁用的树节点标记为红色
   * @param val 
   */ 
  _isDisable(val: string) { 
    if(val.slice(val.length-4,val.length-1) == '已禁用') {
      return true;
    }
    return false;
  }

  /**
   * 展开所有树节点
   */ 
  private _expandAll() {
    this.treeData.forEach(node => {
      this.expandRecursive(node, true);
    });
  }

  // 递归
  private expandRecursive(node: TreeNode, isExpand: boolean) {
    node.expanded = isExpand;
    if (node.children) {
      node.children.forEach(childNode => {
        this.expandRecursive(childNode, isExpand);
      });
    }
  }

}
